using System;
using System.Collections.Generic;
using System.Text;
using System.Globalization;

namespace GarbageTruck.DayOfTheYear
{
    public class DayOfTheYear : ITemporalExpression
    {
        #region CONSTRUCTORS

        public DayOfTheYear()
        {
        }

        public DayOfTheYear(string expresion)
        {
            this.Number = int.Parse(expresion);
        }

        public DayOfTheYear(int number)
        {
            this.Number = number;
        }

        #endregion CONSTRUCTORS

        #region FIELDS

        private int m_Number;
        private Calendar calendar = CultureInfo.CurrentCulture.Calendar;

        #endregion FIELDS

        #region PROPERTIES

        public int Number
        {
            get { return m_Number; }
            set { m_Number = value; }
        }

        #endregion PROPERTIES

        #region METHODS

        public bool Contains(DateTime dateTime)
        {
            return (this.Number == calendar.GetDayOfYear(dateTime));
        }

        public DateTime? GetNextOcurrence(DateTime dateTime)
        {
            DateTime nextOcurrence = new DateTime();
            if (Number > 0)
            {
                if (dateTime.Date.AddDays(-Number).Year < dateTime.Year)
                {
                    nextOcurrence = new DateTime(dateTime.Year, 1, 1);
                }
                else
                {
                    nextOcurrence = new DateTime(dateTime.Year + 1, 1, 1);
                }
            }
            else
            {
                if (dateTime.Date.AddDays(-Number).Year > dateTime.Year)
                {
                    nextOcurrence = new DateTime(dateTime.Year, 12, 31);
                }
                else
                {
                    nextOcurrence = new DateTime(dateTime.Year + 1, 12, 31);
                }
            }

            int value = (Number < 0 ? -1 : 1);

            return nextOcurrence.AddDays(Number - value);
        }

        public DateTime? GetEventEnd(DateTime dateTime)
        {
            return dateTime;
        }

        public override string ToString()
        {
            return string.Format("DOTY({0})", this.Number);
        }

        #endregion METHODS
    }
}
